package com.dance.webflux.service.impl;

import com.dance.webflux.entity.User;
import com.dance.webflux.service.UserService;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    /**
     * 创建 map 集合存储数据,模拟数据库
     */
    private final Map<Integer,User> users = new HashMap<>();
    {
        this.users.put(1,new User("lucy","nan",20));
        this.users.put(2,new User("mary","nv",30));
        this.users.put(3,new User("jack","nv",50));
    }

    @Override
    public Mono<User> getUserById(int id) {
        // 返回一个或者0个元素
        return Mono.justOrEmpty(users.get(id));
    }

    @Override
    public Flux<User> getAllUser() {
        // 返回多个元素,返回全部的值
        return Flux.fromIterable(this.users.values());
    }

    @Override
    public Mono<Void> saveUserInfo(Mono<User> user) {
        // 处理数据后返回空
        return user.doOnNext(x -> {
            int key = users.size() + 1;
            users.put(key,x);
        }).thenEmpty(Mono.empty());
    }
}
